package com.ede.roverhu.simplebackstage.Activities;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import com.ede.roverhu.simplebackstage.Constant.HandlerConstant;
import com.ede.roverhu.simplebackstage.Engine.MyWebViewClient;
import com.ede.roverhu.simplebackstage.Engine.htmlHander;
import com.ede.roverhu.simplebackstage.Http.HttpClient;
import com.ede.roverhu.simplebackstage.R;
import com.ede.roverhu.simplebackstage.Utils.CookieUtils;
import com.ede.roverhu.simplebackstage.Utils.LogUtils;
import com.ede.roverhu.simplebackstage.Utils.ToastUtils;
import com.loopj.android.http.PersistentCookieStore;

import org.apache.http.cookie.Cookie;

import java.util.List;

public class CourseInfoActivity extends BaseActivity {
    private WebView webView;
    String a = "";
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HandlerConstant.QUERYCLASSTIMETABLEINFO_SUCCESS:
                    LogUtils.e(msg.obj.toString());
                    String s = htmlHander.getCourseinfoHTML(getApplicationContext(), msg.obj.toString());
                    CookieSyncManager.createInstance(getApplicationContext());
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(true);
                    cookieManager.removeSessionCookie();//移除
                    cookieManager.setCookie("wise.xcollege.cn", getCookieText());//cookies是在HttpClient中获得的cookie
                    CookieSyncManager.getInstance().sync();
                    webView.loadDataWithBaseURL("http://wise.xcollege.cn/ms_admin/app/member.php", s, "text/html; charset=UTF-8", null, null);
                   // webView.loadData(s, "text/html; charset=UTF-8", null);
                    break;
                case HandlerConstant.QUERYCLASSTIMETABLEINFO_FAIL:
                    ToastUtils.show(getApplicationContext(), "查询失败");
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);

        Intent intent = getIntent();
        a = intent.getStringExtra("iD");
        webView = (WebView) findViewById(R.id.webview);
        //LogUtils.e(getCookieText());
//            String cookieString = "PHPSESSID="+HttpClient.phpsessid ;
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setAllowFileAccessFromFileURLs(true);
        webView.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");
        webView.setWebViewClient(new MyWebViewClient());
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder b = new AlertDialog.Builder(CourseInfoActivity.this);
                //  b.setTitle("提示");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                b.setCancelable(false);
                b.create().show();
                return true;
            }
        });
        HttpClient.queryCourse(a, handler);
    }

    private String getCookieText() {
        PersistentCookieStore myCookieStore = new PersistentCookieStore(CourseInfoActivity.this);
        List<Cookie> cookies = myCookieStore.getCookies();
        LogUtils.d("cookies.size() = " + cookies.size());
        CookieUtils.setCookies(cookies);
        for (Cookie cookie : cookies) {
            LogUtils.d(cookie.getName() + " = " + cookie.getValue());
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < cookies.size(); i++) {
            Cookie cookie = cookies.get(i);
            String cookieName = cookie.getName();
            String cookieValue = cookie.getValue();
            if (!TextUtils.isEmpty(cookieName)
                    && !TextUtils.isEmpty(cookieValue)) {
                sb.append(cookieName + "=");
                sb.append(cookieValue + ";");
            }
        }
        LogUtils.d("cookie ==>" + sb.toString());
        return sb.toString();
    }

    class InJavaScriptLocalObj {
        @JavascriptInterface
        public void showSource(String html) {
            LogUtils.e(html);
            if (html.contains("修改成功")) {
                ToastUtils.show(CourseInfoActivity.this, "修改成功");
                HttpClient.queryCourse(a, handler);
            }
        }
    }

    /**
     *
     */
}
